//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;

        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
function showCustom(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}

document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    // 模拟点击第一个带有 active 类的导航链接
    const activeLink = document.querySelector('.nav-link.active');
    if (activeLink) {
        const targetId = activeLink.dataset.target;
        const targetContent = document.getElementById(targetId);
        navLinks.forEach(navLink => navLink.classList.remove('active'));
        contentAreas.forEach(content => content.classList.remove('active'));
        activeLink.classList.add('active');
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            contentAreas.forEach(content => content.classList.remove('active'));
            this.classList.add('active');
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                targetContent.classList.add('active');
            }
        });
    });
    const tables = document.querySelectorAll('.adminManagement-table');
    tables.forEach(function (table) {
        const selectAll = table.querySelector('.selectAll');
        const rowCheckboxes = table.querySelectorAll('.rowCheckbox');

        selectAll.addEventListener('change', function () {
            const isChecked = this.checked;
            rowCheckboxes.forEach(function (checkbox) {
                checkbox.checked = isChecked;
            });
        });

        rowCheckboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(rowCheckboxes).every(function (cb) {
                    return cb.checked;
                });
                selectAll.checked = allChecked;
            });
        });
    });
    $(document).ready(function () {
        const rowsPerPage = 4; // 每页显示的行数，需与后端默认 pageSize 一致
        const $tableBody = $('#table-body');
        const $pageNav = $('#pageNav');
        let currentPage = 1;
        let totalPages = 1;

        $tableBody.on('click', '.reportedit, .deletebtn, .editbtns', function (event) {
            const $btn = $(event.target);
            const reportId = $btn.data('id'); // 统一通过data-id获取举报ID
            const action = $btn.hasClass('reportedit') ? '详情' :
                $btn.hasClass('deletebtn') ? '驳回' :
                    $btn.hasClass('editbtns') ? '通过' : '';
            switch (action) {
                case '详情':
                    const detailReport = document.querySelectorAll(".reportedit")
                    detailReport.forEach(btn => {
                        btn.addEventListener('click', function () {
                            console.log(132)
                            showDetail(btn);
                        });
                    });
                    break;
                case '驳回':
                    handlePostAction(reportId, '驳回', '/admin/toApproveTheReportedInfo'); // 驳回逻辑
                    break;
                case '通过':
                    handlePostAction(reportId, '通过', '/admin/toRejectTheReportInfo'); // 通过逻辑
                    break;
            }
        });


        // 初始化加载第一页数据
        loadPage(1);

        // 加载指定页数据
        function loadPage(pageNumber) {
            currentPage = pageNumber;

            $.ajax({
                type: 'GET',
                url: '/admin/getReportInfoFromManagerWithPaging', // 后端分页接口
                data: {
                    pageNum: pageNumber,
                    pageSize: rowsPerPage
                },
                success: function (response) {
                    console.log('后端返回数据:', response);
                    const reportList = response.list || [];
                    const postUserList = response.postUserList || []; // 假设后端返回这个数组
                    const reporterList = response.reporterList || []; // 假设后端返回这个数组
                    totalPages = response.totalPage || 1;

                    $tableBody.empty();
                    if (reportList.length > 0 && postUserList.length > 0 && reporterList.length > 0) {
                        reportList.forEach((report, index) => {
                            // 使用当前循环索引从用户列表中获取对应数据
                            const reporter = reporterList[index] || '未知';
                            const postUser = postUserList[index] || '未知';

                            const row = $('<tr>')
                                .attr('data-id', report.id)
                                .append(
                                    $('<td>').html(`<input type="checkbox" class="rowCheckbox" data-id="${report.id}">`),
                                    $('<td>').text(postUser), // 显示具体用户
                                    $('<td>').text(reporter), // 显示具体用户
                                    $('<td>').text(report.reportReason),
                                    $('<td>').html(`<div class="contents">${report.content}</div>`),
                                    $('<td>')
                                        .append($('<button class="reportedit">').attr('data-id', report.id).attr('data-index', index).text('详情')),
                                    $('<td>')
                                        .append($('<button class="deletebtn">').attr('data-id', report.id).text('驳回'))
                                        .append($('<button class="editbtns text-xl">').attr('data-id', report.id).text('通过'))
                                );
                            $tableBody.append(row);
                        });
                        $pageNav.show();
                    } else {
                        $tableBody.html('<div  class="text-center">无未审核的帖子</div>');
                        $pageNav.hide();
                    }

                    updatePagination();
                },
                error: function (error) {
                    console.error('分页数据加载失败:', error);
                    $tableBody.html('<tr><td colspan="7" class="text-center">加载失败，请重试</td></tr>');
                    $pageNav.hide();
                }
            });
            //查询
            const $tableBody = $('#table-body');
            const $notice = $('#notice');

            $('#checkkey-button').click(function () {
                const searchTerm = $('#check').val().trim().toLowerCase();
                if (!searchTerm) {
                    showCustomAlert('请输入查询关键词', 3000);
                    return;
                }

                $.ajax({
                    type: 'GET',
                    url: '/admin/behindManagerReport', // 后端搜索接口
                    data: {
                        query: searchTerm,
                        pageNum: currentPage
                    },
                    success: function (response) {
                        $tableBody.empty();
                        $notice.hide();

                        // 解析HTML响应
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(response, 'text/html');

                        // 提取所有举报行并过滤
                        const reportRows = Array.from(doc.querySelectorAll('#table-body tr'))
                            .filter(row => {
                                // 搜索范围：举报人、被举报人、举报内容、举报原因
                                const reporteder = row.querySelector('td:nth-child(3)')?.textContent.toLowerCase() || '';
                                return (

                                    reporteder.includes(searchTerm)
                                );
                            });

                        if (reportRows.length === 0) {
                            $notice.show();
                            return;
                        }

                        // 渲染过滤后的行
                        reportRows.forEach(row => {
                            const reportId = row.getAttribute('data-id') || row.getAttribute('th:data-id');

                            const cells = row.querySelectorAll('td');
                            const reporter = cells[1].textContent.trim(); // 第3列
                            const reporteder = cells[2].textContent.trim(); // 第4列
                            const reportcontent = cells[3].textContent.trim(); // 第5列
                            const reportreason = cells[5].textContent.trim(); // 第6列
                            const static = cells[4].querySelector('.cl')?.textContent.trim() || '未知状态'; // 第7列

                            // 创建新行
                            const newRow = $('<tr>')
                                .attr('data-id', reportId)
                                .append(`<td><input type="checkbox" class="rowCheckbox" data-id="${reportId}"></td>`)
                                .append(`<td>${reporter}</td>`)
                                .append(`<td>${reporteder}</td>`)
                                .append(`<td>${reportcontent}</td>`)
                                .append(`<td>${reportreason}</td>`)
                                .append(`<td><button class="cl" data-status="${reportId}">${static}</button></td>`)
                                .append(`<td>
                            <button class="deletebtn" data-id="${reportId}">驳回</button>
                            <button class="editbtns text-xl" data-id="${reportId}">通过</button>
                        </td>`);

                            $tableBody.append(newRow);
                        });
                    },
                    error: function (error) {
                        console.error('查询失败:', error);
                        $tableBody.html('<div  class="text-center">查询失败，请稍后重试</div>');
                    }
                });
            });

        }

        // 更新分页导航
        function updatePagination() {
            $pageNav.empty(); // 清空原有导航

            // 上一页按钮
            const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
            if (currentPage === 1) {
                $prevBtn.addClass('disabled'); // 第一页时禁用
            } else {
                $prevBtn.click(function (e) {
                    e.preventDefault();
                    loadPage(currentPage - 1);
                });
            }
            $pageNav.append($prevBtn);

            // 页码按钮（显示当前页附近的页码）
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // 左侧省略号
            if (startPage > 1) {
                $pageNav.append($('<span>').text('...'));
            }

            // 页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const $pageBtn = $('<a href="#" class="num">').text(i);
                if (i === currentPage) {
                    $pageBtn.addClass('active'); // 高亮当前页
                } else {
                    $pageBtn.click(function (e) {
                        e.preventDefault();
                        loadPage(i);
                    });
                }
                $pageNav.append($pageBtn);
            }

            // 右侧省略号
            if (endPage < totalPages) {
                $pageNav.append($('<span>').text('...'));
            }

            // 下一页按钮
            const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
            if (currentPage === totalPages) {
                $nextBtn.addClass('disabled'); // 最后一页时禁用
            } else {
                $nextBtn.click(function (e) {
                    e.preventDefault();
                    loadPage(currentPage + 1);
                });
            }
            $pageNav.append($nextBtn);
        }
    });
    document.querySelectorAll('.editbtns.text-xl:last-child').forEach(button => {
        button.addEventListener('click', function () {
            const postId = this.getAttribute('data-id');
            handlePostAction(postId, '通过', '/admin/toApproveTheReportedInfo');
        });
    });

// 单个操作：驳回按钮
    document.querySelectorAll('.deletebtn').forEach(button => {
        button.addEventListener('click', function () {
            const postId = this.getAttribute('data-id');
            handlePostAction(postId, '驳回', '/admin/toRejectTheReportInfo');
        });
    });

// 单个操作处理函数
    function handlePostAction(postId, actionText, apiUrl) {
        confirms(`确定要${actionText}这个举报吗？`, (isconfimed) => {
            if (isconfimed) {
                $.ajax({
                    url: `${apiUrl}?id=${postId}`,
                    type: 'GET',
                    success: function () {
                        showCustomAlert(`${actionText}成功`, 3000);
                        location.reload(); // 刷新页面更新状态
                    },
                    error: function (error) {
                        console.error(`${actionText}失败`, error);
                        showCustomAlert(`${actionText}失败，请稍后再试`, 3000);
                    }
                });
            }
        })
    }

// 全选/取消全选功能
    $('.selectAll').change(function () {
        $('.rowCheckbox').prop('checked', this.checked);
        updateButtonState(); // 更新批量按钮状态
    });

// 单个复选框变化时更新批量按钮状态
    $('.rowCheckbox').change(updateButtonState);

// 更新批量按钮状态（有选中项则启用按钮）
    function updateButtonState() {
        const hasChecked = $('.rowCheckbox:checked').length > 0;
        $('#check-button, #pass-button').prop('disabled', !hasChecked);
    }

// 批量驳回按钮
    $('#check-button').click(function () {
        const checkedIds = getCheckedIds();
        if (!checkedIds.length) return; // 无选中项则退出

        confirms(`确定要驳回选中的 ${checkedIds.length} 个举报吗？`, (isConfirmed) => {
            if (isConfirmed) {
                // 用户确认后执行批量驳回
                processBatchAction(checkedIds, '驳回', '/admin/toRejectTheReportInfo');
            }
        });
    });

// 批量通过按钮
    $('#pass-button').click(function () {
        const checkedIds = getCheckedIds();
        if (!checkedIds.length) return; // 无选中项则退出

        confirms(`确定要通过选中的 ${checkedIds.length} 个举报吗？`, (isConfirmed) => {
            if (isConfirmed) {
                // 用户确认后执行批量通过
                processBatchAction(checkedIds, '通过', '/admin/toApproveTheReportedInfo');
            }
        });
    });

// 获取所有选中项的ID
    function getCheckedIds() {
        return $('.rowCheckbox:checked').map(function () {
            return $(this).attr('data-id');
        }).get(); // 转换为数组返回
    }

// 批量处理函数（循环调用接口处理每个选中项）
    function processBatchAction(ids, actionText, apiUrl) {
        let successCount = 0;
        let failedCount = 0;
        let currentIndex = 0;

        // 禁用批量按钮防止重复操作
        $('#check-button, #pass-button').prop('disabled', true);

        // 递归处理下一个ID
        function processNext() {
            if (currentIndex >= ids.length) {
                // 全部处理完成后提示结果
                let message = `${actionText}完成：成功 ${successCount} 个，失败 ${failedCount} 个`;
                showCustomAlert(message, 3000);
                location.reload(); // 刷新页面更新状态
                return;
            }

            const postId = ids[currentIndex];
            $.ajax({
                url: `${apiUrl}?id=${postId}`,
                type: 'GET',
                success: function () {
                    successCount++;
                    currentIndex++;
                    processNext(); // 处理下一个
                },
                error: function () {
                    failedCount++;
                    currentIndex++;
                    console.error(`${actionText}失败，ID: ${postId}`);
                    processNext(); // 即使失败也继续处理下一个
                }
            });
        }

        // 开始处理第一个ID
        processNext();
    }

// 关闭弹窗功能
    function closeModal() {
        document.getElementById('reportEditModal').style.display = 'none';
    }

// 返回表单
    const backform = document.getElementById('backform');
    backform.addEventListener('click', function () {
        location.reload();
    });
//返回
    const cancelEditPost = document.querySelector('.cancelEditPost');
    cancelEditPost.addEventListener('click',function(){
        reportEditModal.style.display='none';
    })
});